#!/usr/bin/python
# -*- coding: utf8 -*- 
import socket
import time
import sys
import struct
from select import select

class UDPClient:
	
	server = None
	sockfd = None
	target = None
	opponent = None
	player = None
	
	def __init__(self,ip,port):
		self.server = (ip, port)
		self.sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	
	def connection(self):
		pool = '1'.strip()
		self.sockfd.sendto( pool, self.server )
		data, addr = self.sockfd.recvfrom( len(pool)+3 )
		if data != "ok " + pool:
			print >>sys.stderr, "unable to request!"
			return -1
		
		self.sockfd.sendto( "ok", self.server )
		print >>sys.stderr, "request sent, waiting for player 2 ..."
		data, addr = self.sockfd.recvfrom( 6 )
		self.target = self.bytes2addr(data)
		print >>sys.stderr, "connected to %s:%d" % self.target
		return 1
	
	def updatePlayer(self,player):
		player = self.player
		
	def dataExchange(self):
		#img1 = cv.EncodeImage('.png', self.image)
		
		image = ''
		size = []
		while True:
			rfds,_,_ = select( [0, self.sockfd], [], [] )
			if 0 in rfds:
				print 'sending'
				size = self.chunks(self.player.tostring(),115200/8)
				for i in size:
					time.sleep(0.0009)
					self.sockfd.sendto(i, target)
				self.sockfd.sendto('done', target)
				
			elif sockfd in rfds:
				print 'recieving'
				data, addr = sockfd.recvfrom( 115200/8 )
				if 'done' in data:
					self.opponent = image
					#img1 = cv.DecodeImage(img1, True)
					image = ''
				else:
					image += ''.join(data)


	def chunks(self,l, n):
		return [l[i:i+n] for i in range(0, len(l), n)]		
	
	def bytes2addr(self, bytes):
		if len(bytes) != 6:
			raise ValueError, "invalid bytes"
		host = socket.inet_ntoa( bytes[:4] )
		port, = struct.unpack( "H", bytes[-2:] )
		return host, port
